package cn.com.acca.ma.dao.impl;

import cn.com.acca.ma.dao.ConceptBoardDao;
import cn.com.acca.ma.hibernate.util.HibernateUtil;
import cn.com.acca.ma.model.ConceptBoard;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import java.util.Date;
import java.util.List;

public class ConceptBoardDaoImpl extends BaseDaoImpl<ConceptBoardDaoImpl> implements ConceptBoardDao {

    /**
     * 根据name查询
     * @param name
     * @return
     */
    @Override
    public ConceptBoard findByName(String name) {
        session= HibernateUtil.currentSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(ConceptBoard.class);
        criteria.add(Restrictions.eq("name", name));
        ConceptBoard conceptBoard = (ConceptBoard) criteria.uniqueResult();
        session.getTransaction().commit();
        session.close();

        return conceptBoard;
    }

    /**
     * 插入记录
     * @param conceptBoard
     */
    @Override
    public void save(ConceptBoard conceptBoard) {
        session= HibernateUtil.currentSession();
        session.beginTransaction();
        session.save(conceptBoard);
        session.getTransaction().commit();
        session.close();
    }

    /**
     * truncate表
     */
    @Override
    public void truncateTable() {
        session= HibernateUtil.currentSession();
        session.beginTransaction();
        session.createSQLQuery("truncate table concept_board").executeUpdate();
        session.getTransaction().commit();
        session.close();
    }

    /**
     * 批量插入记录
     * @param conceptBoardList
     */
    @Override
    public void batchSave(List<ConceptBoard> conceptBoardList) {
        session= HibernateUtil.currentSession();
        session.beginTransaction();
        for (ConceptBoard conceptBoard: conceptBoardList){
            session.save(conceptBoard);
        }
        session.getTransaction().commit();
        session.close();
    }

    /**
     * 如果不存在，则插入记录
     * @param conceptBoardList
     */
    @Override
    public void batchSaveIfNotExist(List<ConceptBoard> conceptBoardList) {
        session= HibernateUtil.currentSession();
        session.beginTransaction();
        for (ConceptBoard conceptBoard: conceptBoardList){
            Criteria criteria = session.createCriteria(ConceptBoard.class);
            criteria.add(Restrictions.eq("name", conceptBoard.getName()));
            ConceptBoard _conceptBoard = (ConceptBoard) criteria.uniqueResult();
            if (null == _conceptBoard){
                conceptBoard.setCreateTime(new Date());
                session.save(conceptBoard);
            }
        }
        session.getTransaction().commit();
        session.close();
    }
}
